package ynu.lcy.service.impl;


import com.google.gson.Gson;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import ynu.lcy.dao.IBusinessDao;
import ynu.lcy.dao.ITypeDao;
import ynu.lcy.dto.business.BusinessQueryDTO;
import ynu.lcy.dto.business.BusinessRequestDTO;

import ynu.lcy.elememicroserviceserviceclient.service.FileUploadFeignClient;
import ynu.lcy.entity.Business;
import ynu.lcy.entity.BusinessOrderType;
import ynu.lcy.entity.OrderType;
import ynu.lcy.service.BusinessService;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Service
public class BusinessServiceImpl implements BusinessService {
    @Resource
    private IBusinessDao dao;

    @Resource
    private ITypeDao typeDao;

    @Resource
    private FileUploadFeignClient fileUploadFeignClient;


    /**
     * 根据权重进行推荐
     * @return
     * */
    public List<Business> listByWeight(){
        return dao.findAllByOrderByBusinessWeightDesc();
    }

    /**
     * 根据关键字查询
     * @param dto
     * @return
     * */
    public List<Business> listByKeyword(BusinessQueryDTO dto){
        return dao.findBusinessesByBusinessNameContainingAndBusinessAddressContaining(dto.getBusinessName(),dto.getBusinessAddress());
    }

    /**
     * 根据类型商家
     * @param typeId
     * @return
     * */
    @Transactional
    public List<Business> listByType(Long typeId){
        OrderType orderType = typeDao.getReferenceById(typeId);
        List<BusinessOrderType> businessOrderTypes = orderType.getBusinessOrderTypes();
        return businessOrderTypes.stream().map(BusinessOrderType::getBusiness).toList();
    }

    /**
     * 根据id获取信息
     * @param id
     * @return
     * */
    public Business getById(Long id){
        return dao.getReferenceById(id);
    }

    /**
     * 添加商家
     * @param dto
     * @return
     * */
    @Transactional
    public Business add(BusinessRequestDTO dto){
        try {
            //获取标签类型
            List<OrderType> orderTypes = new ArrayList<>();
            if (dto.getBusinessType().size()>0){
                dto.getBusinessType().forEach(typeId ->orderTypes.add(typeDao.getReferenceById(typeId)));
            }
            //上传文件
            String file = fileUploadFeignClient.upload(dto);
            Business business = new Business().create(dto, file,orderTypes);
            return dao.save(business);
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }


}
